# 和大多数后端语言一样，原生是没有前端 json 格式的，要么结构体，要么 dict

from datetime import datetime

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

fake_db = {}


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: str | None = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    # Pydantic model 转 JSON
    json_compatible_item_data = jsonable_encoder(item)
    print(f"item类型 {type(item)},{item}")
    # item类型 <class '21_JSONCompatibleEncoder.Item'>,title='string' timestamp=datetime.datetime(2024, 9, 24, 9, 58, 29, 284000, tzinfo=TzInfo(UTC)) description='string'
    print(f"转换后 {type(json_compatible_item_data)},{json_compatible_item_data}")
    # 转换后 <class 'dict'>,{'title': 'string', 'timestamp': '2024-09-24T09:58:29.284000Z', 'description': 'string'}
    fake_db[id] = json_compatible_item_data
